import React, { Component } from "react";
import { Layout, Form, Button, Divider, notification, Input, message } from "antd";
import "@/style/view-style/login.less";
import { connect } from "react-redux";
import TheImage from "@/components/TheImage";
import { LoadingOutlined } from "@ant-design/icons";
import ParticlesBg from "particles-bg";
import { passwordReg } from "@/utils/regexp";
import { apiPage } from "../../request/system/menu";
import aesUtil from "../../utils/aes";
import { maskNumber } from '@/utils/tools'
// import rsaUtil from "../../utils/rsa";
import { encrypt, decode, getCaptcha } from "@/request/auth";
import { apiViewByUserName } from "@/request/users/index";
import store from '@/store/store'

import { setWithExpiry, getWithExpiry } from '@/utils/tools'
import _ from "lodash";
import { Base64 } from "js-base64";
import JSEncrypt from "jsencrypt";
const mapDispatchToProps = (dispatch) => {
  return {
    updateUser: (data) => {
      dispatch({ type: "set", data });
    },
    updateMenu: (data) => {
      dispatch({ type: "setMenus", data });
    },
    updateIdent: (data) => {
      dispatch({ type: "setIdent", data });
    },
  };
};
const mapStateToProps = (state) => {
  return {
    user: state.user,
    code: "",
  };
};

class Login extends Component {
  componentDidMount() {
    document.getElementById('viewport').setAttribute('content', 'width=device-width, minimum-scale=1.0, initial-scale=1, maximum-scale=1.0, user-scalable=no');

    if (this.props.user) {
      this.props.history.push("/home");
    }
    // let rsaPassword = React.$getrsa('aaa123456')
    // console.log(rsaPassword);
    this.imgChange()

  }

  state = {
    loading: false,
    key: new Date().getTime(),
    url: '',
    mobileCodeDownTime: '发送验证码',
    errorCount: 0,
    mobileCodeExpiry: true || getWithExpiry('mobileCodeExpiry'),

    userMobile: ''
  };
 
  
  /**
   * @desc 登录事件
   * @params object {values} 登录表单提交事件
   * */
  handleSubmit = async (values) => {
    values = { ...values, areaCode: 'admin' }
    console.log(values, 'aaaa');
    const { loginName, password, captcha, mobileCode } = values
    if (!loginName) {
      React.$message({
        type: "warning",
        content: '请输入账号'
      });
      return false

    } else if (!password) {
      React.$message({
        type: "warning",
        content: '请输入密码'
      });
      return false

    } else if (!captcha) {
      React.$message({
        type: "warning",
        content: '请输入图形验证码'
      });
      return false

    }
    // else if (!mobileCode && !this.state.mobileCodeExpiry) {
    //   React.$message({
    //     type: "warning",
    //     content: '请输入短信验证码'
    //   });
    //   return false
    // } else if (this.state.mobileCodeDownTime == '发送验证码' && !this.state.mobileCodeExpiry) {
    //   React.$message({
    //     type: "warning",
    //     content: '请点击发送获取验证码'
    //   });
    //   return false
    // }
    // this.props.history.push("/home");
    // let aesKey = aesUtil.genKey();
    // const rsa = new JSEncrypt();
    // //RSA公钥加密
    // const response = await encrypt({loginName: values.loginName})
    // rsa.setPublicKey(response.data);
    // let data = aesUtil.encrypt(JSON.stringify(values), aesKey)
    // let key = rsa.encrypt(aesKey)
    // const params = {
    //     loginName: values.loginName,
    //     key,
    //     data
    // }
    this.setState({ loading: true });

    React.$post('/admin/auth/admin/login', values).then(data => {
      if (data.code === 0) {

        // this.dbLogin(data.data)
        // return false
        // 原登录逻辑

        sessionStorage.setItem('RSnetToken', data.data.token);
        sessionStorage.setItem('roleName', data.data.roleName);
        this.props.updateUser(data.data);
        React.$post('/admin/sys/ident/getMenuIdentListByUserId').then(res => {
          const ident = res.data.idents.map(v => v.identType)
          this.props.updateIdent(ident)
          sessionStorage.setItem("userMenu", JSON.stringify(res.data.menus))
          sessionStorage.setItem("idents", JSON.stringify(res.data.idents))
          window.location.reload();
          React.$message({
            type: "success",
            content: '登录成功!'
          });
        })

        // 原登录逻辑

      } else {
        this.imgChange()
        // this.setState({
        //   errorCount: this.state.errorCount + 1
        // }, () => {
        //   if (this.state.errorCount >= 5) {
        //     message.destroy()
        //     message.warning({
        //       content: `${data.codeMessage}次数过多暂被锁定，请5分钟后再试`,
        //       maxCount: 1,
        //       top: 100
        //     })
        //     setTimeout(() => {
        //       this.setState({
        //         errorCount: 0
        //       })
        //     }, 60 * 1000 || 5 * 60 * 1000);
        //   } else {
        //     message.destroy()
        //     message.warning({
        //       content: `${data.codeMessage}，还有${5 - this.state.errorCount}次机会，超过将限制5分钟内登录`,
        //       maxCount: 1,
        //       top: 100
        //     })
        //   }
        // })
      }
      this.setState({ loading: false })
    }).catch(e => {

      this.setState({ loading: false })
    })
  };
  // 等保登录修改
  dbLogin(data) {
    sessionStorage.setItem('RSnetToken', data.token);
    sessionStorage.setItem('roleName', data.roleName);
    if (!this.state.mobileCodeExpiry) {
      setWithExpiry('mobileCodeExpiry', 'true', 11160 * 1000 || 7 * 24 * 60 * 60 * 1000) //7天
    }
    this.props.updateUser(data);
    React.$post('/admin/sys/ident/getMenuIdentListByUserId').then(res => {
      const ident = res.data.idents.map(v => v.identType)
      this.props.updateIdent(ident)
      sessionStorage.setItem("userMenu", JSON.stringify(res.data.menus))
      sessionStorage.setItem("idents", JSON.stringify(res.data.idents))
      window.location.reload();
      store.dispatch({
        type: 'IntervalPageActionTime'
      })
      React.$message({
        type: "success",
        content: '登录成功!'
      });
    })
  }

  componentWillUnmount() {
    notification.destroy();
    this.timer && clearTimeout(this.timer);
  }

  /**
   * @desc 切换验证图片
   * */
  imgChange = async () => {
    let res = await getCaptcha(new Date().getTime())
    var binary = "";
    var bytes = new Uint8Array(res);
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
      binary += String.fromCharCode(bytes[i]);
    }
    var base64 = `data:image/png;base64,${window.btoa(binary)}`
    console.log(base64)
    this.setState({
      url: base64,
      key: new Date().getTime(),
    });
  };
  /**
   * @desc 验证码效验规则
   * */
  onChange = (e) => {
    let val = e.target.value.trim();
    if (val.length > 4) {
      val = val.slice(0, 4);
    }
    this.loginForm.setFieldsValue({ captcha: val });
  };
  onMobileCodeChange = (e) => {
    let val = e.target.value.trim();
    if (val.length > 4) {
      val = val.slice(0, 4);
    }
    this.loginForm.setFieldsValue({ mobileCode: val });
  };
  onFinishFailed = (e) => {
    console.log(e, 'aaa');
  }
  getMobileCode = () => {
    const values = this.loginForm.getFieldsValue()
    if (!values.loginName) {
      React.$message({
        type: "warning",
        content: '请输入账号'
      });
      return false
    }
    apiViewByUserName({ loginName: values.loginName }).then(res => {
      if (res.code == 0 && res.data) {

        let timer = null
        this.setState({
          mobileCodeDownTime: 6,
          userMobile: res.data.userMobile
        }, () => {

          timer = setInterval(() => {
            if (this.state.mobileCodeDownTime <= 1) {
              this.setState({
                mobileCodeDownTime: '重新发送'
              })
              clearInterval(timer)
              timer = null
              return false
            }
            this.setState({
              mobileCodeDownTime: this.state.mobileCodeDownTime - 1
            })
          }, 1000);
        })
      }

    })

  }
  render() {
    const { loading, key, code, url, mobileCodeDownTime, errorCount, mobileCodeExpiry, userMobile } = this.state;
    return (
      <Layout className="login animated fadeIn">
        {/* <ParticlesBg
          type="cobweb"
          bg={true}
          className={"canvas-back"}
          style={{ zIndex: 1 }}
          color="#EEEEEE"
        /> */}
        <div className="model">
          <div className="login-form">
            <div className="login-logo"></div>
            <h3>登录 哈奇马管理平台</h3>
            <Divider style={{ margin: "30px auto" }} />
            <Form
              ref={(ref) => {
                this.loginForm = ref;
              }}
              onFinish={this.handleSubmit}
              onFinishFailed={this.onFinishFailed}
            >
              <Form.Item
                className={"form-item"}
                name="loginName"
              // rules={[
              //   { required: true, message: "输入手机号!" },
              //   {
              //     whitespace: true,
              //     message: "不能包含空格字符",
              //   },
              // ]}
              >
                <React.FormInput placeholder="请输入账号" />
              </Form.Item>
              <Form.Item
                className={"form-item"}
                name="password"
              // rules={[{ required: true, message: "请输入密码!" }]}
              >
                <React.FormPassword placeholder="请输入密码" />
              </Form.Item>
              <Form.Item
                className={"captcha-item"}
                name="captcha"
              // rules={[
              //   {
              //     required: true,
              //     message: "请输入验证码!",
              //   },
              //   { validator: this.validator },
              //   { min: 4, message: "验证码为4个字符" },
              //   {
              //     whitespace: true,
              //     message: "不能包含空格字符",
              //   },
              // ]}
              >
                <div>
                  <React.FormInput
                    style={{ width: 130 }}
                    onChange={this.onChange}
                    placeholder="请输入验证码"
                  />
                  <div
                  // className="clearfix code-change-box"
                  >
                    <TheImage
                      placeholder={
                        !url ? <div className="img-center-label">
                          <LoadingOutlined />
                        </div> : false
                      }
                      className={"fl"}
                      // src={"/pro-web/admin/" + "auth/captcha?" + key}
                      src={url}
                      key={key}
                      width={"126px"}
                      height={"50px"}
                      preview={false}
                      onClick={this.imgChange}
                    />
                    {/* <span className="code-change-btn fr" onClick={this.imgChange}>
                      换一张
                    </span> */}
                  </div>
                </div>
              </Form.Item>

              {
                !mobileCodeExpiry &&
                <Form.Item name="mobileCode">
                  <Input
                    style={{
                      width: '130px',
                      height: 50
                    }}
                    placeholder="短信验证码"
                    maxLength={6}
                    onChange={this.onMobileCodeChange}
                  />
                  <Button onClick={this.getMobileCode} disabled={mobileCodeDownTime >= 0} style={{ display: 'inline-block', height: 50, fontSize: 18, marginLeft: 20, width: 126, background: mobileCodeDownTime >= 0 ? '#ddd' : '', color: mobileCodeDownTime >= 0 ? '#000' : '' }} type="primary">{mobileCodeDownTime}{mobileCodeDownTime >= 0 ? 's' : ''}</Button>
                  {mobileCodeDownTime > 0 && <p style={{ color: '#fff', marginTop: 10 }} >验证码已发送至{maskNumber(userMobile, 3, 4)}</p>}

                </Form.Item>
              }


              <Form.Item className={"form-item"}>
                <Button
                  type="primary"
                  htmlType="submit"
                  className="login-form-button"
                  loading={loading}
                  disabled={errorCount >= 5}
                >
                  登录
                </Button>
              </Form.Item>
            </Form>
          </div>
        </div>
      </Layout>
    );
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Login);
